//
//  ViewController.m
//  pictureTouchAction
//
//  Created by 李勇 on 2018/8/11.
//  Copyright © 2018 李勇. All rights reserved.
//

#import "ViewController.h"
#import "DragView.h"
#import "DragViewByPan.h"
#define BARBUTTON(TITLE, SELECTOR)     [[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR]
#define PIC_SIZE 64

@interface ViewController ()

@end

@implementation ViewController



- (void)loadView{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    self.view = [[UIView alloc] init];
    self.view.backgroundColor = [UIColor blackColor];
    
    // Provide a "Randomize" button
    self.navigationItem.rightBarButtonItem = BARBUTTON(@"Randomize", @selector(layoutFlowers));
    
    NSUInteger maxFlowers = 12; // number of flowers to add
    NSArray *flowerArray = @[@"flower1.png", @"flower2.png", @"flower3.png"];
    
    // Add the flowers
    for (NSUInteger i = 0; i < maxFlowers; i++)
    {
        NSString *whichFlower = [flowerArray objectAtIndex:(random() % flowerArray.count)];
        //dragview 是按照触摸底层的方法进行移动
//        DragView *flowerDragger = [[DragView alloc] initWithImage:[UIImage imageNamed:whichFlower]];
        //DragViewByPan 是根据苹果封装的pan手势进行移动
         DragViewByPan *flowerDragger = [[DragViewByPan alloc] initWithImage:[UIImage imageNamed:whichFlower]];
        [flowerDragger setFrame:CGRectMake(0, 0, PIC_SIZE, PIC_SIZE)];
        [self.view addSubview:flowerDragger];
    }
}

- (void)viewDidLoad{
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)viewDidLayoutSubviews{
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [self layoutFlowers];
}

- (void)viewDidDisappear:(BOOL)animated{
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)dealloc{
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}


- (CGPoint)randomFlowerPosition
{
    CGFloat halfFlower = PIC_SIZE/2; // half of the size of the flower
    
    // The flower must be placed fully within the view. Inset accordingly
    CGSize insetSize = CGRectInset(self.view.bounds, 2*halfFlower, 2*halfFlower).size;
    
    // Return a random position within the inset bounds
    CGFloat randomX = random() % ((int)insetSize.width) + halfFlower;
    CGFloat randomY = random() % ((int)insetSize.height) + halfFlower;
    return CGPointMake(randomX, randomY);
}

- (void)layoutFlowers
{
    // Move every flower into a new random place
    [UIView animateWithDuration:0.3f animations: ^(){
        for (UIView *flowerDragger in self.view.subviews)
        {
            flowerDragger.center = [self randomFlowerPosition];
        }
    }];
    
}

@end
